package dialogs
{
	import Classes.pi_events;
	
	import UIFree.ObjectEvent;
	import UIFree.controls.uif_input;
	import UIFree.controls.uif_label;
	import UIFree.uif_component;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class pi_friends extends pi_listWindow {
		private const WIDTH: int = 480;
		private const HEIGHT: int = 400;
		private const USER_SIZE: Point = new Point(80, 125);
		private var users: Array;

		public function pi_friends(parent:uif_component, ax:int=0, ay:int=0) {
			super(parent, ax, ay, WIDTH, HEIGHT, 'tab');
			_content.height = 50;
			title.text = pi_data.FRIEND;
			app['externalserver'].getAllFriends(app['externalserver'].viewer_id, function(data: *): void {
				doResponseFriend(data);
				show();
			}, pi_data.FRIEND_QUERYID);
			
			var inner: Rectangle = getInner();
			(new uif_label(this, inner.x, inner.y + 60, 50, 20, 'lbLabel')).text = pi_data.SEARCH;
			(new uif_input(this, inner.x + 50, inner.y + 60, inner.width - 50, 20, 'minput')).addEvent(Event.CHANGE, function(e: Event): void {
				filterList(e.target.text);
			});
		}
		
		override protected function get areaHeight(): int {
			return 250;
		}
		
		protected function doSelectUser(e: MouseEvent): void {
			app.dispatchEvent(new ObjectEvent(pi_events.SELECTUSER, (e.target as pi_user).userData));
		}
		
		protected function userItemEvents(item: pi_user): pi_user {
			item.addEvent(MouseEvent.CLICK, doSelectUser);
			return item;
		}
		
		protected function filterList(filter: String): void {
			if (filter.length > 1) {
				filter = filter.toUpperCase();
				assignList(users.filter(function(item: Object, index: int, arr: Array): Boolean {
					var sText: String = String(item.first_name + ' ' + item.last_name + ' ' + item.nick).toUpperCase();
					return sText.indexOf(filter) > -1;
				}));
			} else if (filter.length == 0) assignList(users);
		}
		
		protected function assignList(list: Array): void {
			_area.assignList(list, USER_SIZE.x, function(_scroll: uif_component, inner: Rectangle, index: int): pi_user {
				return userItemEvents(new pi_user(_scroll, list[index], inner.x, inner.y, USER_SIZE.x, USER_SIZE.y, 'tabItem_unselect'));   
			}, pi_data.USERS_PERLINE);
		}
		
		public function doResponseFriend(data:*): void {
			users = data;
			assignList(users);
		}
	}
}